<?php
@include ("phpmailer/function.sendmail.php");
function TImport($md)
{
    include_once 'source/'.$md.'/functions.php';
}
function ImportClass($cl)
{
    @include_once 'includes/class_'.$cl.'.php';
}

function debug($message)
{
    $file=$_SERVER['DOCUMENT_ROOT']."/".$GLOBALS['folder_path_root']."docs/log_error.txt";
    $logdata="[".date("d-m-Y/h-i")."-".$_SERVER['REMOTE_ADDR']."] ";
	$logdata.=$message;
	$logdata.="=>".$_SERVER['REQUEST_URI'].">\r\n\r\n";
    $f=@fopen($file,"a");
    if($f)
    {			
        @fwrite($f,$logdata);
        @fclose($f);
    }
}
function csubstr($str,$start,$length)
{
	$str=strip_tags($str);
	$arr=explode(" ",$str);
	$temp="";
	$i=0;
	while(strlen($temp)<$length && $i<count($arr))
	{
		$temp.=$arr[$i++]." ";
	}
	if(strlen($str)>$length)$temp.="...";
	return $temp;
}

function strSplitSub($str,$count)
{
	$return="";
	$countt=0;
	$str=strip_tags($str);
	$length=strlen($str);
	for($i=0;$i<$length;$i++)
	{
		if($str[$i]==" ")
		{
			$countt++;
			if($countt>=$count-1)break;
		}
		$return.=$str[$i];
	}
	if($countt>$count-2)$return.="...";
	return $return;
}

function UpdateOnline()
{
global $ip,$language,$dbsql,$ajax;

	$ip=$_SERVER['REMOTE_ADDR'];
	$datenow=date("Y-m-d H:i:s");
	$url	=$_SERVER['REQUEST_URI'];
	if($ajax===true)
	{
		return;
	}
	$dbsql->query("delete from tblonline where iTime<".(_TIME-60*60),true);
	$sql_select=" select cIp from tblonline where cIp='$ip'";
	$rs=$dbsql->query($sql_select);

	if($dbsql->num_rows($rs)==0)
	{
		$sql_insert="insert into tblonline(cIp,iTime,cUrlEnd,cLanguage,dTimeBegin,iCountPage)
									values('$ip',"._TIME.",'$action','$language','$datenow',0)";
		$dbsql->query($sql_insert,true);
		@addCountRate();
	}else
	{
		$sql_update="update tblonline set
					iTime="._TIME."
				where cIp='$ip' limit 1";
		$dbsql->query($sql_update,true);
	}
	//$rs=$dbsql->query("CALL UpdateOnline('$ip','$url','$language')",true);
}

function addCountRate()
{
global $ip,$language,$dbsql;

	//reset TODAY:
	$sql_update="update tblconfig set cValue='0',cType='".date("d")."' where cName='ratetoday' and cType!='".date("d")."'";
	$dbsql->query($sql_update,true);

	//reset week:
	$sql_update="update tblconfig set cValue='0',cType='".date("W")."' where cName='rateweek' and cType!='".date("W")."'";
	$dbsql->query($sql_update,true);


	//reset month:
	$sql_update="update tblconfig set cValue='0',cType='".date("m")."' where cName='ratemonth' and cType!='".date("m")."'";
	$dbsql->query($sql_update,true);

	//reset year:
	$sql_update="update tblconfig set cValue='0',cType='".date("Y")."' where cName='rateyear' and cType!='".date("Y")."'";
	$dbsql->query($sql_update,true);

	$sql_update="update tblconfig set cValue=cValue+1 where cName='ratetoday' or cName='rateweek' or cName='ratemonth'
					or cName='rateyear' or cName='ratesite'";
	$dbsql->query($sql_update,true);

}

function Exc_AutoLink($str)
{//return $str;
	return $str;
	global $limit_AutoLink;
	for($i=0;$i<count($aKey);$i++)
	{
		$pos=0;
		$count=0;
		while(($pos=stripos($str,$aKey[$i],$pos))!==false)
		{
			$check=true;//echo $pos."|";
			for($j=$pos;$j>0;$j--)
			{				
				if($str[$j]=="<")
				{
					$check=false;
					break;
				}
				if($str[$j]==">")break;
			}
			for($j=$pos;$j<strlen($str);$j++)
			{
				if($str[$j]==">" || (strtolower(substr($str,$j,4))=="</a>"))
				{
					$check=false;
					break;
				}
				if($str[$j]=="<")break;
			}
			if(!$check)
			{
				$pos+=strlen($aKey[$i]);
				continue;
			}
			if($pos>0)$start=$pos-1;
			else $start=$pos;
			$temp1=substr($str,0,$start);
			$temp2=substr($str,$start,strlen($aKey[$i])+5);
			$temp3=substr($str,strlen($temp1.$temp2));
			if(strtolower($temp2)==strtolower($aKey[$i]))
			{
				$temp2.=".";
				$str.=".";
			}
			$se="/(\W|^)(".$aKey[$i].")(\W|$)/i";
			$re='\1<a class="autolink" title="\2" href="'.$aLink[$i].'">\2</a>\3';
			$temp2=preg_replace($se,$re,$temp2,1);	
			$strold=$str;
			$str=$temp1.$temp2.$temp3;
			if($strold!=$str)$count++;
			$pos+=strlen($temp2);
			if($pos>strlen($str))break;			
			if($count>=$limit_AutoLink)break;
		}
	}
	return $str;
}


function ListMenuByPlace($place="all")
{
global $dbsql,$language;
	$place=strtolower($place);
	$iplace=0;
	switch($place)
	{
		case "top":
			$iplace=1;
			break;
		case "left":
			$iplace=2;
			break;
		case "bottom":
			$iplace=3;
			break;
		default:
			$iplace=4;
			break;
	}
		
	$sql_select = "select iId,cName,cUrlString,cType from tblcategory 
			where  (iPlace=$iplace or iPlace=4)  and cLanguage='$language'
			and iStatus='1' order by iOrder";
			
	$rs=$dbsql->query($sql_select);
	$categories=array();
	while ( $result = $dbsql->fetch_array($rs) )
	{
	   if(strpos($result['cUrlString'],".htm")===false)
	   {
	   		$result['cUrlString'].="/";
	   }
	   if($result['cUrlString']=="Home/")
	   {
	   	$result['cUrlString']='';
	   }
	   $categories[] = $result;
	}
	return $categories;
}


function echoLink($url="",$hasEcho=false,$hroot=1)
{
global $root_domain,$folder_path_root;
	if($hroot==1)
	{
		if($url[0]=="/")
		{
			$url=substr($url,1);
		}
		$url= $folder_path_root.$url;
	}
	if($hasEcho==true)
	{
		echo $url;
	}else 
	{
		return $url;
	}
}


function GetIntroImg($pathfile,$thumb=false,$default=true)
{
global $folder_img_upload;

	$path  = $folder_img_upload;
	if($thumb==true)
	{
        $file     = basename($pathfile);
		$pathfile = str_replace($file,"thumbs/".$file,$pathfile);
		$path    .= $pathfile;
	}else
	{
		$path     .= $pathfile;
	}
    
	if(is_file($path))
	{
		return echoLink($path);
	}else if($default==true)
    {
        return echoLink('images/clear.gif');
    }
	return false;
}

function Redirect($url)
{
	//header( "HTTP/1.1 301 Moved Permanently" );
	if($GLOBALS['ajax']==true)
	{
		echo '{"act": "Redirect","url": "'.$url.'"}';
		exit;
	}
	header( "Location: $url" ); 
	exit;
}


function LoadAdvertise($place)
{
global $dbsql,$language;

	$advertises=array();
	$sql_select="select cName,cImageLink,cUrlString,iOpenNew from tbladvertise where iPlace='$place' and iStatus=1 order by iOrder";
	$rs=$dbsql->query($sql_select);
	while ($result=$dbsql->fetch_array($rs)) {
			$advertises[]=$result;
	}
	return $advertises;
}

function Transfer($url,$sec)
{
	return '<meta http-equiv="REFRESH" content="'.$sec.'; url='.$url.'">';
}

function getConfig($name,$default="")
{
    global $dbsql,$language;

	if(is_array($name))
	{
		$loaded=true;
		$configs=array();
		$sql_select='select cName,cValue from tblconfig where ';
		foreach ($name as $i=>$keyname)
		{
			if($i>0)$sql_select.=" or ";
			$sql_select.=" cName='$keyname' ";
			if(!isset($GLOBALS['config_'.$keyname]))
			{
				$loaded=false;
			}
			$configs[$keyname]=$GLOBALS['config_'.$keyname];
		}
		if($loaded)
		{
			return $configs;
		}
		$rs=$dbsql->query($sql_select);
		$configs=array();
		while ($result=$dbsql->fetch_array($rs)) {
			$configs[$result['cName']]=$result['cValue'];
		}
		return $configs;
	}

	if(isset($GLOBALS['config_'.$name]))return $GLOBALS['config_'.$name];

	$sql_select="select cValue from tblconfig where cName='$name'";
	if($result=$dbsql->query_fetch($sql_select))
	{
		$value=$result['cValue'];
		$GLOBALS['config_'.$name]=$value;
	}
	return $value;
}

function getConfigEmail($name)
{
    global $dbsql,$language,$email_admin;
    ImportClass('json');
	$sql_select="select cValue from tblconfig where cName='EmailTemp".$name."' and cLanguage='$language'";
	if($result  =$dbsql->query_fetch($sql_select))
	{
        $result = FJSON::decode($result['cValue']);
        if(!isset($result->email))
        {
            $result->email  = $email_admin;
        }
	}
	return $result;
}

function LoadCategoryRoot($url)
{
    global $dbsql,$language;
    
    $sql_select = "select * from tblcategory where iParentId=0 ";
    if(empty($url))
    {
        $sql_select .= " and cType = 'Home' ";
    }else
    {
        $sql_select .= " and cUrlString='$url' ";
    } 
    $sql_select .=" and cLanguage='$language' ";
    return $dbsql->query_fetch($sql_select);
}

function ListCategoryByParentId($idP)
{
    global $dbsql,$language;
    $idP        = intval($idP);
    $sql_select = "select * from tblcategory where iParentId=$idP and iStatus=1 order by iOrder";
    return $dbsql->load($sql_select);
}

function Split_Page($count_all)
{
global $page,$posts_per_page,$num_page;

	if($page<1)
    {
        $page       = 1;   
    }
	$limitpage		= array();
	$limitpage[0]	= ($page-1) * $posts_per_page;
	$limitpage[1]   = $posts_per_page;
	$num_page   	= ceil($count_all/$posts_per_page);
    
	return $limitpage;
}

function showSplitPage()
{
    global $num_page,$page,$posts_per_page,$ajaxhasScript;
    
    $url          = $_SERVER['REQUEST_URI']; 
    $show_page    = '';
    if ($num_page > 1)
	{
	   $show_page = "<div class='ctr_pages'>";
	   if($page == 1)
       {
            $class_prev     = 'prevn';
            $page_prev      = 1;
            $onclick_prev   = '';
       }
       else
       {
            $class_prev     = 'preva';
            $page_prev      = $page - 1;
            $onclick_prev   = 'onclick="goPage('.$page_prev.')"';
       }
       
       if($page==$num_page)
       {
            $class_next     = 'nextn';
            $page_next      = $num_page;
            $onclick_next   = '';
       }
       else
       {
            $class_next     = 'nexta';
            $page_next      = $page + 1;
            $onclick_next   = 'onclick="goPage('.$page_next.')"';
       }
       
       $show_page .= '<a href="#'.$page_prev.'" class="prevbut '.$class_prev.'" '.$onclick_prev.'>'.getLang("Previous").'</a>';
       $show_page .= '<a href="#'.$page_next.'" class="nextbut '.$class_next.'" '.$onclick_next.'>'.getLang("Next").'</a>';
       $show_page.='</div><div class="clear">&nbsp;</div>';
	}    
    if(!isset($ajaxhasScript) && $ajaxhasScript!==true)
    {
        $show_page .= '<script type="text/javascript">
            ajp=new ajaxLoader; 
            ajp.init({url: "'.$url.'",divtext: "ajaxpage",loading: "ajaxpage",hascache:true});                       
            function goPage(p)
            {                           
                ajp.send("page="+p);
            }
        </script>';
        $ajaxhasScript  = true;
    }   
    return $show_page; 
}

function AjaxTransfer($status,$msg)
{
    ImportClass('json');
    $arrcode    = array("status"=>$status);
    if(is_array($msg))
    {
        foreach($msg as $key => $vl)
        {
            $arrcode[$key] = $vl;
        }
    }else
    {
        $arrcode['msg'] = $msg;
    }

    echo FJSON::encode($arrcode);
    writeLang();
    exit;
}

function getUrlCatByType($type)
{
    global $dbsql,$language,$urlcatbytypes;
    
    if(isset($urlcatbytypes[$type]))
    {
        return $urlcatbytypes[$type];
    }
    $sql_select = "select cUrlString from tblcategory where cType='$type' and cLanguage='$language'";
    $result     = $dbsql->query_fetch($sql_select);
    $urlcatbytypes[$type]   = '/'.$result['cUrlString'];
    return $urlcatbytypes[$type];
}

function getIdByType($type)
{
    global $dbsql,$language,$urlcatbytypes;
    
    $sql_select = "select iId from tblcategory where cType='$type' and cLanguage='$language'";
    $result     = $dbsql->query_fetch($sql_select);
    return $result['iId'];
}

function ListIntOption($select,$start,$end)
{
	$options="<option value=''>".getLang('select')."</option>";
	$options="";
	for($i=$start;$i<=$end;$i++)
	{
		if($i==$select)
		{
			$options.="<option value='$i' selected>$i</option>";
		}else
		{
			$options.="<option value='$i'>$i</option>";
		}
	}
	return $options;
}

function splitPrice($number)
{
    while (true) {
        $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
}

function getPriceClient($price,$rel=false,$sameDisplay=true)
{
	$pren=getconfig(array('UnitInput','UnitDisplay','CurrencyUSD'));
	if($rel)
	{
		return $price.' '.$pren['UnitInput'];
	}

	if($pren['CurrencyUSD']==0)$pren['CurrencyUSD']=1;
	if($sameDisplay==false)
	{
		$pren['UnitDisplay']=($pren['UnitDisplay']=='USD')? 'VND' : 'USD';
	}
	if($pren['UnitInput']!=$pren['UnitDisplay'])
	{
		if($pren['UnitInput']=='USD') {
			$price=$price*$pren['CurrencyUSD'];
		}else if($pren['UnitInput']=='VND'){
			$price=$price/$pren['CurrencyUSD'];
		}
	}
	$price=preg_replace("(([0-9]*)(.)([0-9]{2})([0-9]*))","$1$2$3",$price);
	return splitPrice($price).' '.$pren['UnitDisplay'];
}

function ListAdv($place)
{
    global $dbsql,$language;
    
    $sql_select = "select * from tbladvertise where iPlace=$place";
    return $dbsql->load($sql_select);
}

function getAdvType($file)
{
    $height = "170";
    $width  = "165";
    if(substr($file,strlen($file)-3,3)!='swf')
    {
        echo '<img src="'.$file.'" width='.$width.' border=0>';
    }else
    {
        echo '<object classid="clsid27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'.$width.'" height="'.$height.'">
              <param name="movie" value="'.$file.'" />
              <param name="quality" value="high" />
              <param name="allowScriptAccess" value="always" />
              <param name="wmode" value="transparent">
                 <embed src="'.$file.'"
                  quality="high"
                  type="application/x-shockwave-flash"
                  WMODE="transparent"
                  width="'.$width.'"
                  height="'.$height.'"
                  pluginspage="http://www.macromedia.com/go/getflashplayer"
                  allowScriptAccess="always" />
            </object>';
    }
}
?>